package com.aqiang.day0528_shop.main.view.activity

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.aqiang.day0528_shop.R
import com.aqiang.day0528_shop.main.adapter.SearchGoodsAdapter
import com.aqiang.day0528_shop.main.contract.GoodsTypeContract
import com.aqiang.day0528_shop.main.contract.SearchGoodsContract
import com.aqiang.day0528_shop.main.entity.BaseEntity
import com.aqiang.day0528_shop.main.entity.SearchGoodsEntity
import com.aqiang.day0528_shop.main.presenter.SearchGoodsPresenter
import com.aqiang.lib_core.common.SLog
import com.aqiang.lib_core.mvp.BaseActivity
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_goods.*
import kotlinx.coroutines.Deferred
import org.jetbrains.anko.startActivity

class GoodsActivity : BaseActivity<SearchGoodsContract.SearchGoodsPresenter>(),SearchGoodsContract.SearchGoodsView {

    private var searchGoodsAdapter:SearchGoodsAdapter? = null
    private var name:String = ""
    private var id:Int = 16
    override fun bindLatout(): Int {
        return R.layout.activity_goods
    }

    override fun createPresenter() {
        mPresenter = SearchGoodsPresenter(this)
    }

    override fun initView(savedInstanceState: Bundle?) {
       rv_act_goods.layoutManager = LinearLayoutManager(this)
    }

    override fun initData() {
        name = intent.getStringExtra("name")
        id = intent.getIntExtra("id",16)
        //SLog.d("${name}")
        if(name != null){
            //et_act_goods_srarch.setText(name)
            tv_act_goods_bar.text = "${name}  ×"
            tv_act_goods_bar.visibility = View.VISIBLE
        }
        doAsynTask {
            mPresenter!!.searchGoods()
        }
    }

    override fun initEvent() {
        tv_act_goods_bar.setOnClickListener {
            tv_act_goods_bar.visibility = View.GONE
            et_act_goods_srarch.setText(name)
        }
    }

    override fun getKeyWork(): String {
        return name
    }

    override fun initAdapter(goods: Deferred<BaseEntity<List<SearchGoodsEntity>>>) {
        doUiThread(goods,{
            val data = it.data
            if(searchGoodsAdapter == null){
                searchGoodsAdapter = SearchGoodsAdapter(R.layout.item_srearch_goods,data)
                rv_act_goods.adapter = searchGoodsAdapter
                searchGoodsAdapter!!.setOnItemClickListener { adapter, view, position ->
                    startActivity<ProductDetailsActivity>(
                        "data" to Gson().toJson(data.get(position))
                    )
                }
            }else{
                searchGoodsAdapter!!.notifyDataSetChanged()
            }
        })
    }
    override fun getType(): Int {
        return id
    }
}
